<template>
  <div class="app-container flex flex-col">
    <div class="app-container__section shrink-0">
      <plus-search
          v-bind="getSearchBinds()"
          :columns="columns"
      ></plus-search>
      <div></div>
    </div>

    <div class="app-container__section pb-0 flex-1 shrink-0">
      <plus-table
          v-bind="getBinds()"
          :columns="columns"
          :height="500"
      >
        <template #title>
          <table-title />
        </template>
        <template #plus-cell-dictType="{ row }">
          <router-link class="link-type" :to="`/system/dict-data/index/${row.dictId}`">{{row.dictType}}</router-link>
        </template>
        <template #toolbar>
          <el-button
              type="primary"
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['system:dict:add']"
          >
            新增
          </el-button>
          <el-button
              type="danger"
              icon="Delete"
              :disabled="selection.length === 0"
              @click="handleDelete"
              v-hasPermi="['system:dict:remove']"
          >
            删除
          </el-button>
          <el-button
              type="danger"
              icon="Refresh"
              @click="handleRefreshCache"
              v-hasPermi="['system:dict:remove']"
          >
            刷新缓存
          </el-button>
          <ClockTimer :task="getList"/>
          <SearchAreaControl v-model="showSearchForm"/>
        </template>
        <template #plus-cell-action="scope">
          <el-tooltip effect="dark" content="修改" placement="top">
            <el-button
                type="primary"
                link
                icon="EditPen"
                @click="handleUpdate(scope.row)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top">
            <el-button
                type="danger"
                link
                icon="Delete"
                @click="handleDelete(scope.row)"
            >
            </el-button>
          </el-tooltip>
        </template>
      </plus-table>
    </div>

    <!-- 添加或修改参数配置对话框 -->
    <DialogView
        :title="title"
        v-model="open"
        @close="onDialogClose"
        @cancel="cancel"
        @submit="submitForm(dialogFormRef)"
    >
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="rules" label-width="80px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model.trim="dialogForm.dictName" :maxlength="30" placeholder="请输入字典名称"/>
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model.trim="dialogForm.dictType" :maxlength="30" placeholder="请输入字典类型"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dialogForm.status">
            <el-radio
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="dialogForm.remark" type="textarea" :maxlength="200" show-word-limit
                    placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
    </DialogView>
  </div>
</template>

<script setup name="Dict">
import { addType, delType, getType, listType, refreshCache, updateType } from "@/api/system/dict/type.js";
import { PlusTable } from "plus-pro-components";
import ClockTimer from "@/components/PlusTableEnhance/Toolbar/clockTimer.vue";
import SearchAreaControl from "@/components/PlusTableEnhance/Toolbar/searchAreaControl.vue";
import { useTablePage } from "@/hooks/useTablePage.js";
import DialogView from "@/components/Viewers/DialogView.vue";
import { RouterLink } from "vue-router";
import { Validator } from "@/utils/formValidator.js";
import { formatRangeTime } from "@/utils/index.js";
import { useActions } from "@/hooks/useActions.js";
import TableTitle from "@/components/Table/TableTitle.vue";

const {proxy} = getCurrentInstance();
const {sys_normal_disable} = proxy.useDict("sys_normal_disable");

const { deleteAction } = useActions()

const title = ref("");
const open = ref(false);
const dialogForm = ref({
  dictId: undefined,
  dictName: undefined,
  dictType: undefined,
  status: "0",
  remark: undefined
});
const dialogFormRef = ref();
const rules = {
  dictName: [
    {min: 0, max: 30, trigger: "blur"},
    {required: true, fieldName: "字典名称", validator: Validator.commonName, trigger: "blur"}
  ],
  dictType: [
    {required: true, message: "字典类型不能为空", trigger: "blur"}
  ]
};

const searchForm = ref({});

const {
  gLoadingStatus: loadingStatus,
  gReset: reset,
  gGetList: getList,
  gSelection: selection,
  gShowSearchForm: showSearchForm,
  getBinds,
  getSearchBinds
} = useTablePage(listType, {
  searchForm,
  beforeRequest(query) {
    let {createTime, ...rest} = query;
    let timeRange = formatRangeTime(createTime, undefined, "YYYY-MM-DD");
    return {
      ...rest,
      ...timeRange
    };
  }
});

const columns = computed(() => {
  return [
    {
      label: "字典名称",
      prop: "dictName",
      tableColumnProps: {
        align: "center"
      }
    },
    {
      label: "字典类型",
      prop: "dictType",
      tableColumnProps: {
        align: "center"
      }
    },
    {
      label: "状态",
      prop: "status",
      valueType: "select",
      options: sys_normal_disable,
      tableColumnProps: {
        align: "center"
      }
    },
    {
      label: "备注", prop: "remark", hideInSearch: true,
      tableColumnProps: {
        align: "center"
      }
    },
    {
      label: "创建时间",
      prop: "createTime",
      valueType: "date-picker",
      fieldProps: {type: "daterange", valueFormat: "YYYY-MM-DD"},
      tableColumnProps: {
        align: "center"
      }
    },
    {
      label: "操作", prop: "action", width: 100, hideInSearch: true,
      tableColumnProps: {
        align: "center"
      }
    }
  ];
});

function handleDelete(row) {
  deleteAction({
    api: delType,
    selection: row.dictId || selection.value,
    uniqueKey: 'dictId',
    confirmMsg: ({ids}) => `是否确认删除字典编号为${ids}的数据项？"`
  }).then(() => {
    getList();
  })
}

function handleRefreshCache() {
  refreshCache().then(() => {
    proxy.$modal.msgSuccess("刷新成功");
  });
}

function resetDialogForm() {
  dialogForm.value = {
    dictId: undefined,
    dictName: undefined,
    dictType: undefined,
    status: "0",
    remark: undefined
  };
  dialogFormRef.value?.resetFields();
}

function onDialogClose() {
  resetDialogForm();
  open.value = false;
}

function handleAdd() {
  open.value = true;
  title.value = "添加字典类型";
}

function handleUpdate(row) {
  resetDialogForm();
  const dictId = row.dictId || this.ids;
  getType(dictId).then(response => {
    dialogForm.value = response.data;
    open.value = true;
    title.value = "修改字典类型";
  });
}

function submitForm(formEl) {
  if (!formEl) return;
  formEl.validate().then(() => {
    if (dialogForm.value?.dictId) {
      updateType(dialogForm.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        getList();
      });
    } else {
      addType(dialogForm.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
    }
  });
}

function cancel() {
  onDialogClose();
}
</script>
